package com.brush.brushcommon.common.sys.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.brushcommon.common.sys.mapper.UserMapper;
import com.brush.brushcommon.common.sys.pojo.User;
import com.brush.brushcommon.common.sys.service.UserService;
import com.brush.brushcommon.dto.Result;
import com.brush.brushcommon.redis.RedisConstants;
import com.brush.brushcommon.utils.*;
import com.brush.brushcommon.dto.sys.LoginDto;
import com.brush.brushcommon.vo.sys.LoginVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 * @author debug
 * @since 2024-07-15
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 账号密码登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public Result login(LoginDto loginDto) {
        if (StringUtils.isBlank(loginDto.getUsername()) && StringUtils.isBlank(loginDto.getPassword())) {
            return Result.fail(500, "用户名或密码不能为空~");
        }
        if (StringUtils.isBlank(loginDto.getCaptchaKey())) {
            return Result.fail(500, "验证码key不能为空~");
        }
//      验证码是够通过
        if (!CaptchaImageUtil.verify(loginDto.getCaptchaKey(), loginDto.getCaptchaValue())) {
            return Result.fail(500, "验证码错误~");
        }
//        查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, loginDto.getUsername()));
        if (Objects.isNull(user)) {
            return Result.fail(500, "用户不存在~");
        }
//   对比密码
        String UserPwd = user.getPwd();
        String beforePwd = Md5.getMD5(loginDto.getPassword().getBytes(StandardCharsets.UTF_8));
        if (!UserPwd.equals(beforePwd)) {
            return Result.fail(500, "密码错误~");
        }
//        生成token
        String token = JwtHelper.createToken(user.getId(), user.getUsername());
        LoginVO loginVO = new LoginVO().setAccessToken(token).setTokenType("Bearer");
        return Result.success(loginVO);
    }

    @Override
    public Result sendCode(String phone) {
        //采用正则校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            return Result.fail(500, "手机格式错误");
        }
        //TODO 后续改为第三方短信平台
        //采用工具类生成随机验证码
        String code = RandomUtil.randomString(6);
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.SECONDS);
        log.info("验证码：{}", code);
        return Result.success(code);
    }

    /**
     * 手机号登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public Result phoneLogin(LoginDto loginDto) {
        //采用正则校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(loginDto.getPhone());
        if (phoneInvalid) {
            return Result.fail(500, "手机格式错误");
        }

        Boolean isHaveKey = stringRedisTemplate.hasKey(RedisConstants.LOGIN_CODE_KEY + loginDto.getPhone());
        if (!isHaveKey) {
            return Result.fail(500, "验证码失效");
        }
//        获取redis进行比较
        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginDto.getPhone());
        if (!code.equals(loginDto.getCode())) {
            return Result.fail(500, "验证码错误");
        }
        LoginVO loginVO = new LoginVO();
        loginVO.setTokenType("Bearer");
//       判断是否存在
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, loginDto.getPhone()));
        if (Objects.isNull(user)) {
            user=new User().setPhone(loginDto.getPhone()).setUsername(RandomUtil.randomString(6)).setType(0).setVxAvatar("https://oss.youlai.tech/youlai-boot/2023/05/16/811270ef31f548af9cffc026dfc3777b.gif");
            //添加用户
            userMapper.insert(user);
        }
//        返回token
        loginVO.setAccessToken(JwtHelper.createToken(user.getId(), user.getUsername()));
        return Result.success(loginVO);
    }
}
